package cn.xxd.xxdorderportal.controller;

import cn.xxd.OrderServiceInterface;
import cn.xxd.common.IdWorker;
import cn.xxd.common.UserUtil;
import cn.xxd.entity.*;
import cn.xxd.service.ContentService;
import cn.xxd.service.ShopCartService;
import cn.xxd.xxdssointerface.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Controller
public class OrderController {

    @Reference(version = "1.0.0", timeout = 100000)
    private UserService userService;

    @Reference(version = "1.0.0", timeout = 100000)
    private ContentService contentService;

    @Reference(version = "1.0.0", timeout = 100000)
    private OrderServiceInterface orderService;

    @Reference(version = "1.0.0", timeout = 100000)
    private ShopCartService shopCartService;

    @Value("${AUTHORITY}")
    private String AUTHORITY;

    @Value("${URL}")
    private String URL;

    @Value("${ORDER_URL}")
    private String ORDER_URL;

    @Value("${HOMEURL}")
    private String HOMEURL;

    @RequestMapping("/order")
    public String checkout(HttpServletRequest request, Model model) {

        // 获取当前用户id
        String id = UserUtil.getCurrentUserId(request, AUTHORITY);
        // 获取当前用户信息
        ShopUser shopUser = userService.getShopUserByUserId(id);
        // 获取地址
        List<XxdAddress> addrList = userService.getAddressList(id);
        // 获取商品
        List<XxdItem> items = contentService.findHomeCartItem(Integer.valueOf(id));

        // 总价
        double total = 0;
        for (XxdItem item : items) {
            total += item.getSum();
        }

        model.addAttribute("addrList", addrList);
        model.addAttribute("shopUser", shopUser);
        model.addAttribute("total", total);
        model.addAttribute("items", items);
        model.addAttribute("url", URL);
        model.addAttribute("FLAG", "noflag");
        model.addAttribute("HOMEURL", "HOMEURL");
        return "checkout";
    }

    @RequestMapping("/orderById")
    public String checkoutByItemId(String itemId, String num, HttpServletRequest request, Model model) {

        // 获取当前用户id
        String id = UserUtil.getCurrentUserId(request, AUTHORITY);
        // 获取当前用户信息
        ShopUser shopUser = userService.getShopUserByUserId(id);
        // 获取地址
        List<XxdAddress> addrList = userService.getAddressList(id);
        // 获取单件商品
        List<XxdItem> items = contentService.getOneItemById(itemId);

        long total = 0;

        if (items != null) {
            if (items.get(0).getNewPrice() != null) {
                total = items.get(0).getNewPrice();
            } else {
                total = items.get(0).getPrice();
            }
        } else {
            // 待定
        }

        total = total * Integer.valueOf(num);

        items.get(0).setNum(Integer.valueOf(num));

        model.addAttribute("addrList", addrList);
        model.addAttribute("shopUser", shopUser);
        model.addAttribute("total", total);
        model.addAttribute("items", items);
        model.addAttribute("url", URL);
        model.addAttribute("FLAG", "FLAG"); // 直接购买的标记
        model.addAttribute("HOMEURL", "HOMEURL");
        return "checkout";
    }

    @PostMapping("/order/make")
    @ResponseBody
    public ReturnT make(String title, String price, String itemNum, String itemTotal, String itemId, String FLAG, ShopUser shopUser, HttpServletRequest request, Model model) {

        XxdOrder xxdOrder = new XxdOrder();
        String userId = UserUtil.getCurrentUserId(request, AUTHORITY);
        if (!"FLAG".equals(FLAG)) {
            // 添加至购物袋购买
            // 获取购物袋信息
            double total = 0;
            int num = 0;
            List<XxdItem> items = contentService.findHomeCartItem(Integer.valueOf(userId));
            for (XxdItem item : items) {
                total += item.getSum();
                num++;
            }
            // 生成订单
            String orderId = "X" + new IdWorker(1, 1, 1).nextId();
            xxdOrder.setOrder_id(orderId);
            xxdOrder.setCreateTime(new Date());
            xxdOrder.setItemCount(num);
            xxdOrder.setPayType(null); // 暂未使用
            xxdOrder.setPayTime(null); // 暂未使用
            xxdOrder.setDistribution_date(null); // 暂未使用
            xxdOrder.setDistribution_mode(null); // 暂未使用
            xxdOrder.setItems_total(BigDecimal.valueOf(total));
            xxdOrder.setFreight(null); // 暂未使用
            xxdOrder.setShopId(null); // 暂未使用
            xxdOrder.setUserId(Integer.valueOf(userId));
            xxdOrder.setPayment(null);
            xxdOrder.setStatus("0");
            int result = orderService.save(xxdOrder);
            if (result <= 0) {
                return new ReturnT(500, "failed");
            }


            XxdOrderItem xxdOrderItem = new XxdOrderItem();
            for (XxdItem item : items) {
                xxdOrderItem.setItemId(Integer.valueOf(item.getItemId()));
                xxdOrderItem.setSkuId(null);
                xxdOrderItem.setSpuId(null);
                xxdOrderItem.setItemName(item.getTitle());
                xxdOrderItem.setItemNum(item.getNum());
                xxdOrderItem.setItemPrice(BigDecimal.valueOf(item.getPrice())); // 不做是否降价判断
                xxdOrderItem.setItemTotal(BigDecimal.valueOf(item.getSum()));
                xxdOrderItem.setOrderId(xxdOrder.getOrder_id());
                xxdOrderItem.setShopId(null);
                xxdOrderItem.setDel(0);
                int i = orderService.saveOrderItem(xxdOrderItem);
                if (i <= 0) {
                    return new ReturnT(500, "failed");
                }
            }
            // 购物车清除
            shopCartService.changeStatus(userId);
            return new ReturnT(200, xxdOrder.getOrder_id());
        } else {
            // 直接购买
            // 生成订单
            String orderId = "X" + new IdWorker(1, 1, 1).nextId();
            xxdOrder.setOrder_id(orderId);
            xxdOrder.setCreateTime(new Date());
            xxdOrder.setItemCount(1);
            xxdOrder.setPayType(null); // 暂未使用
            xxdOrder.setPayTime(null); // 暂未使用
            xxdOrder.setDistribution_date(null); // 暂未使用
            xxdOrder.setDistribution_mode(null); // 暂未使用
            xxdOrder.setItems_total(new BigDecimal(itemTotal));
            xxdOrder.setFreight(null); // 暂未使用
            xxdOrder.setShopId(null); // 暂未使用
            xxdOrder.setUserId(Integer.valueOf(userId));
            xxdOrder.setPayment(null);
            xxdOrder.setStatus("0");
            int result = orderService.save(xxdOrder);
            if (result <= 0) {
                return new ReturnT(500, "failed");
            }

            XxdOrderItem xxdOrderItem = new XxdOrderItem();
            xxdOrderItem.setItemId(Integer.valueOf(itemId));
            xxdOrderItem.setSkuId(null);
            xxdOrderItem.setSpuId(null);
            xxdOrderItem.setItemName(title);
            xxdOrderItem.setItemNum(Integer.valueOf(itemNum));  // 这里不填
            xxdOrderItem.setItemPrice(new BigDecimal(price));
            xxdOrderItem.setItemTotal(new BigDecimal(itemTotal));
            xxdOrderItem.setOrderId(xxdOrder.getOrder_id());
            xxdOrderItem.setItemId(Integer.valueOf(itemId));
            xxdOrderItem.setShopId(null);
            xxdOrderItem.setDel(0);
            int i = orderService.saveOrderItem(xxdOrderItem);
            if (i <= 0) {
                return new ReturnT(500, "failed");
            }

            return new ReturnT(200, xxdOrder.getOrder_id());
        }

    }

}

